﻿using System;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels;
using System.Windows;
using System.Windows.Data;
using FU.Capstones.IMS.Web.Common;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.DataContracts;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.EventArgs;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.Respondents;
using FU.Capstones.IMS.Web.Silverlight.Models;
using FU.Capstones.IMS.Web.Silverlight.Popups;
using Microsoft.Practices.Prism.Commands;
using Navigation.Silverlight;

namespace FU.Capstones.IMS.Web.Silverlight.ViewModels
{
    public class MaterialOrderListViewModel : ViewModelBase
    {

        public MaterialOrderListViewModel()
        {
            Model = new MatarialOrderListModel();
            ((MatarialOrderListModel) Model).GetOrderCollectionByParameterCompleted += DoGetOrderCollectionByParameterCompleted;
            ((MatarialOrderListModel) Model).GetEmployeeCollectionCompleted += DoGetEmployeeCollectionCompleted;
            ((MatarialOrderListModel)Model).SearchOrderCompleted += DoSearchOrderCompleted;
            ((MatarialOrderListModel)Model).GetSingleOrderCompleted += DoGetSingleOrderCompleted;
            ((MatarialOrderListModel)Model).DeleteOrderCompleted += DoDeleteOrderCompleted;
            ((MatarialOrderListModel)Model).GetCollectionOrderCompleted += DoGetCollectionOrderCompleted;
            ServiceCallCounter += ((MatarialOrderListModel) Model).GetEmployeeCollectionAsync(IsShowAll);
            ServiceCallCounter += ((MatarialOrderListModel)Model).GetOrderCollectionAsync(IsShowAll);
            MaterialOrderCriteria = new OrderCriteria();
            CanEditOrAdd = CurrentUser.CanAddOrderMaterial || CurrentUser.CanEditOrderMaterial;
            CanEditOrAdd = CurrentUser.CanAddOrderProduct || CurrentUser.CanEditOrderProduct;
            CanAdd = CurrentUser.CanAddOrderMaterial || CurrentUser.CanAddOrderProduct;

        }

        void DoDeleteOrderCompleted(object sender, FeedbackCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);
                if (e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Collapsed;
                    ServiceCallCounter += ((MatarialOrderListModel)Model).GetOrderCollectionAsync(IsShowAll);
                    
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }
        void DoSearchOrderCompleted(object sender,CollectionFeedbackCompletedEventArgs<Order> e)
        {

            if (e.Error != null)
            {
                Message = e.Error.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    OrderCollection = new PagedCollectionView(e.Result.Data);
                    OrderCollection.PageSize = 10;
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }
        void DoGetEmployeeCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Employee> e)
        {
            if (e.Error!=null)
            {
                Message = e.Result.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    EmployeeCollection = new ObservableCollection<Employee>(e.Result.Data);
                    Employee nullEmployee = new Employee();
                    nullEmployee.FullName = "Tất cả";
                    nullEmployee.EmployeeID = -1;
                    employeeCollection.Insert(0,nullEmployee);
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }
        void DoGetOrderCollectionByParameterCompleted(object sender, CollectionFeedbackCompletedEventArgs<Order> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    OrderCollection = new PagedCollectionView(e.Result.Data);
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;

        }
        void DoGetCollectionOrderCompleted(object sender, CollectionFeedbackCompletedEventArgs<Order> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    OrderCollection = new PagedCollectionView(e.Result.Data);
                    //OrderCollection.
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;

        }
        void DoGetSingleOrderCompleted(object sender, SingleFeedbackCompletedEventArgs<Order> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                Message = e.Result.Message;
                if (!e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Visible;
                }
                else
                {
                    MessageVisibility = Visibility.Collapsed;
                    DetailOrder = e.Result.Data;
                    NavigationData ngdDetailOrder = new NavigationData();
                    ngdDetailOrder.NavigationUri = WebConstants.NavigationPages.MaterialOrderList;
                    ngdDetailOrder.Data = DetailOrder;
                    NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportMaterialOrder, ngdDetailOrder);
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;

        }


        #region declare orderCollection to hold all order

        private PagedCollectionView orderCollection;
        public PagedCollectionView OrderCollection
        {
            get { return orderCollection; }
            set
            {
                if (!ReferenceEquals(orderCollection, value))
                {
                    orderCollection = value;
                    RaisePropertyChanged(() => OrderCollection);
                }
            }
        }

        #endregion

        #region Declare command
        //create SearchCommand to search order
        private DelegateCommand<object> searchCommand;
        public DelegateCommand<object> SearchCommand
        {
            get
            {
                if (searchCommand == null)
                {
                    searchCommand = new DelegateCommand<object>(DoSearchCommand);
                }
                return searchCommand;
            }
        }

        //create CreateCommand to add new an order of material
        private DelegateCommand<Order> createCommand;
        public DelegateCommand<Order> CreateCommand
        {
            get
            {
                if (createCommand == null)
                {
                    createCommand = new DelegateCommand<Order>(DoCreateCommand);
                }
                return createCommand;
            }
        }

        //create EditCommand
        private DelegateCommand<object> editCommand;
        public DelegateCommand<object> EditCommand
        {
            get
            {
                if (editCommand == null)
                {
                    editCommand = new DelegateCommand<object>(DoEditCommand);
                }
                return editCommand;
            }
        }
        #endregion

        #region Implement command
        #region ShowAllCommand

        private DelegateCommand<object> showAllCommand;
        public DelegateCommand<object> ShowAllCommand
        {
            get
            {
                if (showAllCommand == null)
                {
                    showAllCommand = new DelegateCommand<object>(DoShowAllCommand);
                }
                return showAllCommand;
            }
        }

        private void DoShowAllCommand(object obj)
        {
            ServiceCallCounter += ((MatarialOrderListModel)Model).GetOrderCollectionAsync(IsShowAll);
        }

        #endregion
        #region Implement SearchCommand
        private void DoSearchCommand(object obj)
        {
            
            #region set value for isimport and isdelete

            MaterialOrderCriteria.IsImported = null;
            MaterialOrderCriteria.IsDeleted = null;
            if (IsImport)
            {
                if (!IsUnImport)
                {
                    MaterialOrderCriteria.IsImported = true;
                }

            }
            else
            {
                if (IsUnImport)
                {
                    MaterialOrderCriteria.IsImported = false;
                }
            }
            if (IsDelete)
            {
                if (!IsUnDelete)
                {
                    MaterialOrderCriteria.IsDeleted = true;
                }
            }
            else
            {
                if (IsUnDelete)
                {
                    MaterialOrderCriteria.IsDeleted = false;
                }
            }
            #endregion

            //defaul IsMaterial is null to search all
            #region set value for isMaterial

            MaterialOrderCriteria.IsMaterial = null;
            if (IsMaterial)
            {
                if (!IsProduct)
                {
                    MaterialOrderCriteria.IsMaterial = true;
                }
            }
            else
            {
                if (IsProduct)
                {
                    MaterialOrderCriteria.IsMaterial = false;
                }
            }

            #endregion

            #region Add minute to fromDate
            if (MaterialOrderCriteria.ExportedOrImportedDateFrom != null)
            {
                string newTodateString = string.Format("{0:yyyy-MM-dd}", MaterialOrderCriteria.ExportedOrImportedDateFrom) + " 00:00:00";
                MaterialOrderCriteria.ExportedOrImportedDateFrom = DateTime.Parse(newTodateString);
            }

            #endregion


            #region Add minute to toDate

            if (MaterialOrderCriteria.ExportedOrImportedDateTo != null)
            {
                string newTodateString = string.Format("{0:yyyy-MM-dd}", MaterialOrderCriteria.ExportedOrImportedDateTo)+" 23:59:59";
                MaterialOrderCriteria.ExportedOrImportedDateTo = DateTime.Parse(newTodateString);
            }
            
            #endregion


            #region set value for isAllOrderCode
                
            if (string.IsNullOrWhiteSpace(MaterialOrderCriteria.OrderCode))
            {
                MaterialOrderCriteria.IsAllOrderCode = 1;
            }
            else
            {
                MaterialOrderCriteria.OrderCode = MaterialOrderCriteria.OrderCode.Trim();
                MaterialOrderCriteria.IsAllOrderCode = 0;
            }

            #endregion
            
            ServiceCallCounter += ((MatarialOrderListModel)Model).SearchOrderAsync(MaterialOrderCriteria);
           
            Message = "Searching for employees!";
        }

        #endregion

        #region Implement EditCommand

        private void DoEditCommand(object obj)
        {   
            int orderId = (int) obj;
            NavigationData ngdDetailOrder = new NavigationData();
            ngdDetailOrder.NavigationUri = WebConstants.NavigationPages.MaterialOrderList;
            ngdDetailOrder.Data = orderId;
            NavigationManager.NavigateTo(WebConstants.NavigationPages.OrderDetail, ngdDetailOrder);
        }

        #endregion

        #region Implement CreateCommand

        private void DoCreateCommand(object obj)
        {
            ImportExportConfirmationPopup popup = new ImportExportConfirmationPopup();
            popup.Show();
            popup.Closed += (sender, e) =>
            {
                //if (popup.IsMaterial)
                //{
                //    NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportMaterialOrder);
                //}
                //else
                //{
                //    NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportProductOrder);
                //}
                //if (popup.DialogResult.HasValue)
                //{
                //    if (popup.DialogResult == true)
                //    {
                //        NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportMaterialOrder);
                //    }
                    
                //}
                //else
                //{
                //    NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportProductOrder);
                //}
                
                //if (popup.DialogResult == null)
                //{
                //    NavigationManager.NavigateTo(WebConstants.NavigationPages.ExportProductOrder);
                //}
            };
            
        }

        #endregion

        #region Delete command
        private DelegateCommand<int?> deleteCommand;
        public DelegateCommand<int?> DeleteCommand
        {
            get
            {
                if (deleteCommand == null)
                {
                    deleteCommand = new DelegateCommand<int?>(DoDeleteCommand);
                }
                return deleteCommand;
            }
        }

        private void DoDeleteCommand(int? obj)
        {
            if (obj.HasValue)
            {
                DeleteConfirmationPopup popup = new DeleteConfirmationPopup();
                popup.Show();
                popup.Closed += (sender, e) =>
                                    {
                                        if (popup.DialogResult.HasValue && popup.DialogResult.Value)
                                        {
                                            ServiceCallCounter +=((MatarialOrderListModel)Model).DeleteOrderAsync(obj.Value);
                                            currentOrderID = obj.Value;
                                            Message = "Deleting the selected employee!";
                                        }
                                    };
            }
        }

        #endregion

        #endregion

        #region biding data to combobox

        private ObservableCollection<Employee> employeeCollection;
        public ObservableCollection<Employee> EmployeeCollection
        {
            get { return employeeCollection; }
            set
            {
                if (!ReferenceEquals(employeeCollection, value))
                {
                    employeeCollection = value;
                    RaisePropertyChanged(() => EmployeeCollection);
                }
            }
        }
        
        private OrderCriteria materialOrderCriteria;
        public OrderCriteria MaterialOrderCriteria
        {
            get { return materialOrderCriteria; }
            set
            {
                if (!ReferenceEquals(materialOrderCriteria, value))
                {
                    materialOrderCriteria = value;
                    RaisePropertyChanged(() => MaterialOrderCriteria);
                }
            }
        }
        #endregion

        #region detailOrder
        private Order detailOrder;
        public Order DetailOrder
        {
            get { return detailOrder; }
            set
            {
                if (!ReferenceEquals(detailOrder, value))
                {
                    detailOrder = value;
                    RaisePropertyChanged(() => DetailOrder);
                }
            }
        }

        #endregion

        private int currentOrderID;
        private bool isDelete;
        public bool IsDelete
        {
            get { return isDelete; }
            set
            {
                isDelete = value;
                RaisePropertyChanged(() => IsDelete);
                 
            }
        }
        private bool isUnDelete;
        public bool IsUnDelete
        {
            get { return isUnDelete; }
            set
            {
                isUnDelete = value;
                RaisePropertyChanged(() => IsUnDelete);

            }
        }
        private bool isImport;
        public bool IsImport
        {
            get { return isImport; }
            set
            {
                isImport = value;
                RaisePropertyChanged(() => IsImport);

            }
        }
        private bool isUnImport;
        public bool IsUnImport
        {
            get { return isUnImport; }
            set
            {
                isUnImport = value;
                RaisePropertyChanged(() => IsUnImport);

            }
        }
        private bool isMaterial;
        public bool IsMaterial
        {
            get { return isMaterial; }
            set
            {
                isMaterial = value;
                RaisePropertyChanged(() => IsMaterial);

            }
        }
        private bool isProduct;
        public bool IsProduct
        {
            get { return isProduct; }
            set
            {
                isProduct = value;
                RaisePropertyChanged(() => IsProduct);

            }
        }
        #region Implementation of INavigationAware

        public override void OnNavigate(object extraData)
        {
           
        }

        public override void OnLeave()
        {
            //throw new NotImplementedException();
        }

        #endregion
    }
}
